package com.power.sifa.approve.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.plf.common.utils.StringUtil;
import com.plf.core.base.model.Ha_attachment;
import com.plf.core.base.service.Ha_attachmentService;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.approve.dao.Apl_arrive_personDao;
import com.power.sifa.approve.model.Apl_arrive_person;
import com.power.sifa.approve.model.pageInfo.Apl_arrive_personPageInfo;
import com.power.sifa.approve.service.Apl_arrive_personService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;

/**
 *  送达详情送达人业务层实现
 */
@Service
public class Apl_arrive_personServiceImpl extends BaseServiceImpl implements Apl_arrive_personService {

    @Autowired
    private Apl_arrive_personDao dao;

    @Resource
    private Ha_attachmentService ha_attachmentService;

    @Override
    public Apl_arrive_person getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Apl_arrive_person apl_arrive_person) {
    	// save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (apl_arrive_person.getPrimaryKey() != null) {
        	 Apl_arrive_person apl_arrive_personfDb = dao.findById(apl_arrive_person.getPrimaryKey()).orElse(null);
             if(apl_arrive_personfDb != null) {
                BeanUtils.copyProperties(apl_arrive_person, apl_arrive_personfDb);
                dao.save(apl_arrive_personfDb);
                return;
             }
        }
        dao.save(apl_arrive_person);
    }

    @Override
    public void removeById(String id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Apl_arrive_person> findAll(Apl_arrive_personPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        }else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber()<=1 ? 0 : pageInfo.getPageNumber()-1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }
    
    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<String> ids) {
        dao.removeByIds(ids);
    }
    
    @Override
	public List<Apl_arrive_person> findAll() {
		return dao.findAll();
	}
	
	@Override
	public void saveAll(List<Apl_arrive_person> list) {
		dao.saveAll(list);
	}

    @Override
    public List<Apl_arrive_person> findPersonByRecordIds(List<String> recordIds) {
        List<Apl_arrive_person>  personList = dao.findPersonByRecordIds(recordIds);
        if (CollectionUtil.isNotEmpty(personList)) {
            personList.stream().forEach(person -> person.geneText());
            findAttachMentByMeterial(personList);
            return personList;
        }
        return Collections.emptyList();
    }

    private void findAttachMentByMeterial(List<Apl_arrive_person>  personList) {
        if (CollectionUtil.isNotEmpty(personList)) {
            personList.stream().forEach(person -> {
                if (!StringUtil.isEmpty(person.getPhotoinfo())) {
                    String photoinfo = person.getPhotoinfo();
                    List<String> attachmentIds = Arrays.asList(photoinfo.split(","));
                    Map<String, Ha_attachment> ha_attachmentMap = ha_attachmentService.getHa_attachmentsByIds(attachmentIds);
                    if (ObjectUtil.isNotNull(ha_attachmentMap)) {
                        List<Ha_attachment> fileList = new ArrayList<>();
                        attachmentIds.stream().forEach(attachmentId -> {
                            fileList.add(ha_attachmentMap.get(attachmentId));
                        });
                        person.setPhotoInfoList(fileList);
                    }
                }
            });
        }
    }

    @Override
    public void removeByRecordIds(List<String> recordIds) {
        dao.removeByRecordIds(recordIds);
    }

    @Override
    public List<Apl_arrive_person> findPersonByPhone(String phone) {
        Specification<Apl_arrive_person> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.equal(root.get("phone"), phone)
        ).getRestriction();
        return dao.findAll(specification);
    }



    /**
     * 通过号码查询对应的送达信息
     * @param pageInfo
     * @return
     */
    public List<Map<String,Object>> findArriveListByPhone(Apl_arrive_personPageInfo pageInfo) {
        return dao.findArriveListByPhone(pageInfo);
    }
}
